#include "daemon_process.h"
#include <stdlib.h>
#include "thirdparty/log.c/log.h"

extern char **environ;

int daemon_process_init(Subprocess *subprocess, char *submodule)
{
    subprocess->pathname = PATHNAME;
    subprocess->argv = malloc(3 * sizeof(char *));
    if (subprocess->argv == NULL)
    {
        log_warn("Not enough memory for subprocess %s", submodule);
        return -1;
    }
    subprocess->argv[0] = PATHNAME;
    subprocess->argv[1] = submodule;
    subprocess->argv[2] = NULL;

    subprocess->envp = environ;
    subprocess->pid = -1;
    return 0;
}

int daemon_process_run(Subprocess *subprocess)
{
    subprocess->pid = fork();

    if (subprocess->pid < 0)
    {
        // 启动失败
        log_warn("Fork failed for subprocess %s", subprocess->argv[1]);
        return -1;
    }
    else if (subprocess->pid == 0)
    {
        // 子进程
        if (execve(subprocess->pathname, subprocess->argv, subprocess->envp) < 0)
        {
            log_error("Execve failed for subprocess %s", subprocess->argv[1]);
            exit(EXIT_FAILURE);
        }
    }

    // 父进程
    log_info("Subprocess %s started", subprocess->argv[1]);
    return 0;
}
